import FileUtil from "./FileUtil";
import RNFetchBlob from "react-native-fetch-blob";

/** logUtil */
export default class L {
    static LOG_FILE_PATH: string = RNFetchBlob.fs.dirs.SDCardDir + "/RNLOG/";

    static IS_SHOW_LOG_AND_PRINT    : boolean = true;               // 是否控制台打印
    static IS_WRITE_TO_FILE         : boolean = true;               // 日志写入文件开关
    static LOG_PATH_SDCARD_DIR      : string = L.LOG_FILE_PATH;     // 日志文件在sdcard中的路径
    static SDCARD_LOG_FILE_SAVE_DAYS: number = 30;                  // sd卡中日志文件的最多保存天数
    static LOGFILEName              : string = ".txt";              // 本类输出的日志文件名称

    /** 打印 */
    static logOnly(msg: Object): void {
        if (!L.IS_SHOW_LOG_AND_PRINT) return;
        L._show("", msg.toString());
    }

    static logOnly3(object: Object, tag: string, msg: Object): void {
        if (!L.IS_SHOW_LOG_AND_PRINT) return;
        L._show(object.toString(), tag + "," + msg.toString());
    }

    /** 打印&写入文件 */
    static logAndWrite(object: Object, tag: string, msg: Object): void {
        L.logOnly3(object, tag, msg);
        if (L.IS_WRITE_TO_FILE) L._writeLogToFile(object.toString(), tag ,  msg.toString());
    }

    static _show(tag: string, log: string): void {
        console.log(tag + ":" + log)
    }

    /** 打开日志文件并写入日志 **/
    static _writeLogToFile(clazz: string, tag: string, text: string): void {
        let nowTime: Date = new Date();
        let dateStr: string = nowTime.Format("yyyy-MM-dd");
        let timeStr: string = nowTime.Format("yyyy-MM-dd hh:mm:ss");

        let fileName: string = L.LOG_PATH_SDCARD_DIR + dateStr + L.LOGFILEName;
        let fileContent: string = timeStr + ":" + clazz + " " + tag + " " + text + "\n";
        FileUtil.appendFile(fileName, fileContent);
    }

    /** 删除指定日期前的日志文件 */
    static _doDelFile(): void {
        let fileName = L.LOG_PATH_SDCARD_DIR + L._getPreMonth() + L.LOGFILEName;
        FileUtil.deleteFile(fileName);
    }

    /**
     * 获取上一个月
     * @date 格式为yyyy-mm-dd的日期，如：2014-01-25
     */
    static _getPreMonth(): string {
        let date: Date = new Date().Format("yyyy-MM-dd");
        let arr = date.split('-');
        let year = arr[0];      //获取当前日期的年份
        let month = arr[1];     //获取当前日期的月份
        let day = arr[2];       //获取当前日期的日
        let days = new Date(year, month, 0);
        days = days.getDate();  //获取当前日期中月的天数
        let year2 = year;
        let month2 = parseInt(month) - 1;
        if (month2 === 0) {
            year2 = parseInt(year2) - 1;
            month2 = 12;
        }
        let day2 = day;
        let days2 = new Date(year2, month2, 0);
        days2 = days2.getDate();
        if (day2 > days2) {
            day2 = days2;
        }
        if (month2 < 10) {
            month2 = '0' + month2;
        }
        let t2 = year2 + '-' + month2 + '-' + day2;
        return t2;
    }
}
